package cn.lin.web.servlet;

import cn.lin.domain.User;
import cn.lin.service.UserService;
import cn.lin.serviceImpl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author 君未洋
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        //获取数据
        String verifycode = req.getParameter("verifycode");
        //获取下验证码
        String checkcode_server = (String) req.getSession().getAttribute("CHECKCODE_SERVER");
        //获取验证码
        req.getSession().removeAttribute("CHECKCODE_SERVER");

        if (verifycode == null || !checkcode_server.equalsIgnoreCase(verifycode)) {
            //输入的验证码不正常
            req.getSession().setAttribute("login_msg", "验证码输入错误!");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }


        Map<String, String[]> map = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        UserService service = new UserServiceImpl();
        User login = service.login(user);
        if (login == null) {
            //登录失败
            req.getSession().setAttribute("login_msg", "用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        } else {
            req.getSession().setAttribute("user", login);
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        }

    }
}
